package cc.cix.hq.org.controller;


import cc.cix.hq.common.core.entity.constant.StringConstant;
import cc.cix.hq.common.core.entity.org.Menu;
import cc.cix.hq.org.dto.query.QueryMenuReq;
import cc.cix.hq.org.dto.request.MenuReq;
import cc.cix.hq.org.service.IMenuService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cix
 */
@Api(tags = "菜单管理")
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/menu")
public class MenuController {

    private final IMenuService menuService;

    @ApiOperation("菜单列表")
    @GetMapping
    public Map<String, Object> listMenu(QueryMenuReq dto) {
        Menu menu = BeanUtil.toBean(dto, Menu.class);
        return menuService.listMenu(menu);
    }

    @ApiOperation("权限码列表")
    @GetMapping("/permissions")
    public Map<String, Object> listPermissions() {
        Map<String, Object> result = new HashMap<>(1);
        result.put("permissions", menuService.listUserPermission());
        return result;
    }

    @ApiOperation("添加菜单")
    @PreAuthorize("hasAuthority('menu:add')")
    @PostMapping
    public void addMenu(@Valid @RequestBody MenuReq dto) {
        Menu menu = BeanUtil.toBean(dto, Menu.class);
        menuService.createMenu(menu);
    }

    @ApiOperation("删除菜单")
    @PreAuthorize("hasAuthority('menu:delete')")
    @DeleteMapping("/{menuIds}")
    public void deleteMenus(@PathVariable String menuIds) {
        menuService.deleteMenuByIds(StrUtil.splitTrim(menuIds, StringConstant.COMMA));
    }

    @ApiOperation("更新菜单")
    @PreAuthorize("hasAuthority('menu:update')")
    @PutMapping
    public void updateMenu(@Valid @RequestBody MenuReq dto) {
        Menu menu = BeanUtil.toBean(dto, Menu.class);
        menuService.updateMenu(menu);
    }

}
